package com.xcc.server.encoder;

import com.alibaba.fastjson.JSON;
import com.xcc.server.domains.vo.Message;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: xcc
 * @Date: 2021/2/4 16:02
 * @Description:
 */
public class MessageEncoder extends MessageToMessageEncoder<Message> {

    private final Charset charset;

    public MessageEncoder() {
        this(Charset.defaultCharset());
    }

    public MessageEncoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        }
        this.charset = charset;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        if (null == msg) {
            return;
        }
        String s = JSON.toJSONString(msg);
        s = s + "\n";  // 猜想,通过 \n 拆包
        out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(s), charset));
    }
}
